<?php


namespace app\web\controller;


use app\api\controller\v2\Auth;
use app\common\lib\exception\ApiException;
use app\common\lib\Jssdk;
use app\common\lib\Util;
use app\common\model\Recode as RecodeModel;
use app\common\model\User;
use think\Controller;
use think\Env;
use think\Exception;

class ActiveFortuneYear extends Controller
{
    public const AVATAR_WIDTH = 80;
    public const AVATAR_HEIGHT = 80;

    protected function _initialize(): void
    {
        parent::_initialize();
        $res = Util::androidVersion('2.2.0');
        $this->assign('version', $res);
    }

    protected $words = [
        '暴富', '暴瘦', '爆发',
        '安逸', '潇洒', '喜悦',
        '愉悦', '痛快', '得意',
        '欣喜', '幸福', '荣耀',
        '如意', '兴旺', '美满',
        '一夜暴富', '一夜成名', '健健康康',
        '独占鳌头', '硕果累累', '欣欣向荣',
        '相濡以沫', '前程似锦', '春风得意',
        '名列前茅', '德才兼备', '激情四射',
        '神采奕奕', '心满意足', '安居乐业',
        '如愿以偿', '大展宏图', '大功告成',
        '横扫千军', '无懈可击', '日进斗金',
        '飞黄腾达', '平步青云', '登峰造极',
        '金榜题名', '一鸣惊人', '眉飞色舞'
    ];


    public function index()
    {
        //是否是测试环境
        $isTest = false;
        $isInApp = 0;//0：不是在app里打开；1：是在app里打开；
        $app_type = '';
        $uid = '';
        $signPackage = [];
        $sign = -1;

        if ($isTest)
        {
            $type = 0;
            session('year.openid', '123');
            session('year.nickname', '李柏楠');
            session('year.headimgurl', 'http://thirdwx.qlogo.cn/mmopen/vi_32/EhvPAPibRpdsMx6qpbcoMicgBKM8p03bUqb7H5EOQqvj2mOV1FGcG5YfxFx7icE0BWZhndKuicFhVgMc5iccnNo1SRg/132');

//            $type = 1;
//            $headers = json_decode('{"sign":"KkzHDPmQm+bVGlH9DqB6Wq++Yn2Crhb0Ho\/zlmiTGAdlehY+FBqt0tXRLOoQFiP7e\/KXOoopL68Y\/P7fe0gUcp04EnjA5Ovz9hxKtVrU\/j766TxM42wT2NdCcyOHV+aMPY4Wh8Pv4MI9xLEfI83dcgys40ckpiDuFcO+8lq0SmLzY6Gvqbiu5pvtqeY6VU6h","cookie":"Hm_lvt_97bd25fb643e2fbf349c2c61e247fc7a=1577410636,1577410737,1577410804,1577410846","model":"iPhone 6 Plus","connection":"keep-alive","user-agent":"Mozilla\/5.0 (iPhone; CPU iPhone OS 12_1_2 like Mac OS X) AppleWebKit\/605.1.15 (KHTML, like Gecko) Mobile\/16C101","access-token":"ZItpPZF0IW8EaMKCN8ftzYFZpRQjmCzDlBHImDrZisR1MQmOcr+jzJtJy+MugZKiggGAm35BJchSt1awM0IWjg==","did":"4DE0A0E1-CE9A-4F29-A816-7B03CAB15EF5","phone-version":"ios:12.1.2","app-type":"ios","accept-encoding":"br, gzip, deflate","accept-language":"zh-cn","time":"1577411221","version":"1.9.7","accept":"text\/html,application\/xhtml+xml,application\/xml;q=0.9,*\/*;q=0.8","host":"local-wechat.goddessxzns.com","content-type":"","content-length":""}', true);
        }

        if (!$isTest)
        {
            $headers = $this->request->header();
        }
        if (isset($headers['sign']))
        {//在App里请求
            $isInApp = 1;
            $app_type = $headers['app-type'];
            $type = 1;
            //校验token
            try
            {
                $auth = new Auth();
                $auth->checkRequestAuth();
                $uid = $auth->user['id'];
                $map = ['uid' => $uid, 'isself' => 1];
                $recode_info = (new RecodeModel())->getSelfRecode($map);
                if ($recode_info && isset($recode_info['sun']))
                {
                    $sign = explode('-', $recode_info['sun'])[0];
                }
            }
            catch (Exception $e)
            {
                //用户未登录、没有档案、校验失败的情况
                $type = 0;
            }
        } else
        {
            $ua = $_SERVER['HTTP_USER_AGENT'];
            if (strpos($ua, 'MicroMessenger') === false && strpos($ua, 'Windows Phone') === false)
            {
                //使用其他浏览器打开的
                $type = 0;
            } else
            {
                //微信登录
                $type = 2;
                $this->checkLogin();
                $signPackage = (new Jssdk())->getSignPackage();
            }
        }


        $this->assign('data', [
            'host' => $this->request->domain(),
            'ossHost' => Env::get('host.photo') . 'web',
//           'ossHost' => 'http://local-wechat.goddessxzns.com',
            'title' => '测一测你的2020年关键词',
            'share_title' => '测一测你的2020年关键词', // 分享标题
            'share_introduction' => '测过的都暴富、暴瘦啦！', // 分享描述
            'signPackage' => $signPackage,
            'type' => $type,
            'openid' => 2 === $type ? session('year.openid') : $uid,
            'sign' => $sign,//只有$type=1，并且有自己档案的时候，才显示自己的默认选中星座，否则默认为-1
            'isInApp' => $isInApp,
            'app_type' => $app_type
        ]);

        return $this->fetch();
    }

    /**
     * 检查session里是否有  unionid、headimgurl、name 这三个参数，如果为空，那么跳转到微信登录页面
     */
    private function checkLogin(): void
    {
        if (empty(session('year.headimgurl')) || empty(session('year.nickname')))
        {
            $this->redirect('/web/active_fortune_year/weixin_login');
        }
    }

    /**
     * 微信登陆
     */
    public function weixin_login(): void
    {
        $token = '123';
        $appid = config('wechat.mp_appid');
        $domain = Env::get('host.domain');
        $redirect_uri = urlencode($domain . '/web/active_fortune_year/weixin_back');
        header('location:https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $appid . '&redirect_uri=' . $redirect_uri . '&response_type=code&scope=snsapi_userinfo&state=' . $token . '#wechat_redirect');
        exit;
    }

    /**
     * 微信登陆返回
     */
    public function weixin_back(): void
    {
        $appid = config('wechat.mp_appid');
        $appsecret = config('wechat.mp_secret');

        $code = input('get.code');
        if (empty($code)) $this->error('微信授权失败！');

        $token = input('get.state');
        if (empty($token)) $this->error('获取token失败！');
        if (empty(session('year.access_token')))
        {
            $access_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $appsecret . '&code=' . $code . '&grant_type=authorization_code';
            $access_token = json_decode(file_get_contents($access_token_url), false);
            if (isset($access_token->errcode))
            {
                $this->error('授权失败');
            }
            session('year.access_token', $access_token->access_token);
            session('year.refresh_token', $access_token->refresh_token);
            session('year.openid', $access_token->openid);
        }

        $user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . session('year.access_token') . '&openid=' . session('year.openid') . '&lang=zh_CN';
        $user_info = json_decode(file_get_contents($user_info_url), false);
        if (isset($user_info->errcode))
        {
            $access_token_url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=' . $appid . '&grant_type=refresh_token&refresh_token=' . session('year.refresh_token');
            $access_token = json_decode(file_get_contents($access_token_url), true);
            if (isset($access_token['access_token'], $access_token['refresh_token'], $access_token['openid']) && !empty($access_token))
            {
                session('year.access_token', $access_token['access_token']);
                session('year.refresh_token', $access_token['refresh_token']);
                session('year.openid', $access_token['openid']);

                $user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token['access_token'] . '&openid=' . $access_token['openid'] . '&lang=zh_CN';
                $user_info = json_decode(file_get_contents($user_info_url), false);
                if (isset($user_info->errcode))
                {
                    echo '<h1>错误：</h1>' . $user_info->errcode;
                    echo '<br/><h2>错误信息：</h2>' . $user_info->errmsg;
                    exit;
                }
            } else
            {//失败的话，重新授权登录
                $this->redirect('/web/active_fortune_year/weixin_login');
            }
        }
        //把微信返回的参数 保存到session里
        session('year.nickname', $user_info->nickname);
        session('year.sex', $user_info->sex);
        session('year.city', $user_info->city);
        session('year.province', $user_info->province);
        session('year.country', $user_info->country);
        session('year.headimgurl', $user_info->headimgurl);

        $this->redirect('/web/active_fortune_year');
    }

    //开始生成用户头像保存到本地
    public function createAvatar()
    {
        $openid = htmlspecialchars(trim(input('get.openid/s')));
        //0：App未登录；1：App已登录；2：微信登录
        $type = htmlspecialchars(trim(input('get.type/d')));

        $avatar_url = '';
        if (2 === (int)$type)
        {
            $avatar_url = session('year.headimgurl');
        } elseif (1 === (int)$type)
        {
            try
            {
                $user = (new User())->getUserinfo(['id' => $openid]);

                if (preg_match('/^http(s?):\/\/*/', $user['avatar']))
                {
                    $avatar_url = $user['avatar'];
                } else if (!empty($user['avatar']))
                {
                    $avatar_url = Env::get('host.photo') . $user['avatar'];
                }
            }
            catch (ApiException $e)
            {
            }
        }
        if (!empty($avatar_url))
        {
            $this->circleImg($avatar_url, $openid . '.png');
        }

        return show(config('code.success'), '请求成功', []);
    }

    //获取报告index
    public function getReport()
    {
        $openid = htmlspecialchars(trim(input('get.openid/s')));
        //0：App未登录；1：App已登录；2：微信登录
        $type = htmlspecialchars(trim(input('get.type/d')));
        $name = '';
        switch ($type)
        {
            case 0:
                $name = '匿名用户';
                break;
            case 1:
                $user = (new User())->getUserinfo(['id' => $openid]);
                $name = $user['nickname'];
                break;
            case 2:
                $name = session('year.nickname');
                break;
        }
        $index = rand(0, count($this->words) - 1);
        $index_word = $this->words[$index];
        return show(config('code.success'), '请求成功', [
            'name' => $name,
            'index' => $index,
            'index_word' => $index_word
        ]);
    }

    /**
     * 生成报告
     */
    public function report()
    {
        $name = htmlspecialchars(trim(input('get.name/s', '匿名用户')));
        $index = htmlspecialchars(trim(input('get.index/s', '0')));
        $openid = htmlspecialchars(trim(input('get.openid/s', '')));

        try
        {
            if ($index > count($this->words))
            {
                $index = 0;
            }
            header('Content-type: image/png');

            //画布
            $im = @imagecreatetruecolor(710, 1148) or die('Cannot initialize new GD image stream');

            //背景颜色
            $bg_color = imagecolorallocate($im, 72, 92, 176);
            imagefilledrectangle($im, 0, 0, 1500, 2668, $bg_color);// 创建画布

            //背景
            $img_bg = imagecreatefromstring(file_get_contents('./static/active_fortune_year/images/p10/bg.png'));
            imagecopy($im, $img_bg, 0, 0, 0, 0, imagesx($img_bg), imagesy($img_bg));


            //微信 或者 app内用户 的头像
            $filePath = RUNTIME_PATH . 'active_fortune_year' . DS . $openid . '.png';
            if (file_exists($filePath))
            {//文件存在
                $img_avatar = imagecreatefromstring(file_get_contents($filePath));
                imagecopy($im, $img_avatar, 20, 18, 0, 0, self::AVATAR_WIDTH, self::AVATAR_HEIGHT);
            } else
            {//文件不存在，使用默认的
                $img_avatar = imagecreatefromstring(file_get_contents('./static/active_fortune_year/images/p10/avatar.png'));
                imagecopy($im, $img_avatar, 20, 18, 0, 0, self::AVATAR_WIDTH, self::AVATAR_HEIGHT);
            }

            //微信 或者 app内用户 的名字
            $name_color = imagecolorallocate($im, 78, 90, 160);
            imagettftext($im, 30, 0, 133, 70, $name_color, './static/active_fortune_year/nickname.ttf', $name);

            //随机词条 “一鸣惊人” “暴富” 四个字或者两个字
            $key_word = $this->words[$index];
//        $key_word='荣耀';
            $length = strlen($key_word);
            if (6 === $length)
            {
                $x = 220;
            } else
            {
                $x = 120;
            }

            $key_word_color = imagecolorallocate($im, 255, 255, 255);
            imagettftext($im, 90, 0, $x, 340, $key_word_color, './static/active_fortune_year/zk_font.ttf', $key_word);

            imagejpeg($im);
            imagedestroy($im);
            exit();
        }
        catch (\Exception $e)
        {
            throw new ApiException('[' . $e->getFile() . ':' . $e->getLine() . ']' . PHP_EOL . '：[name=' . $name . '&index=' . $index . '&openid=' . $openid . ']' . $e->getMessage());
        }

    }


    /**
     * 生成圆形图片
     * @param $imgpath  图片地址/支持微信、QQ头像等没有后缀的网络图
     * @param $saveName string 保存文件名，默认空。
     * @return resource 返回图片资源或保存文件
     */
    private function circleImg($imgpath, $saveName = '')
    {
        //判断文件是否已经存在，如果存在那么返回，不存在那么生成
        $filePath = RUNTIME_PATH . 'active_fortune_year' . DS . $saveName;
        if (file_exists($filePath))
        {
            return;
        }

        $src_img = imagecreatefromstring(file_get_contents($imgpath));
        $w = imagesx($src_img);
        $h = imagesy($src_img);
        $w = $h = min($w, $h);

        //缩放图片
        $des_w = self::AVATAR_WIDTH;
        $des_h = self::AVATAR_HEIGHT;
        //创建画布
        $zoom_img = imagecreatetruecolor($des_w, $des_h);
        //设置缩放起点
        $des_x = 0;
        $des_y = 0;
        $src_x = 0;
        $src_y = 0;
        imagecopyresampled($zoom_img, $src_img, $des_x, $des_y, $src_x, $src_y, $des_w, $des_h, $w, $h);
        //缩放图片

        $w = self::AVATAR_WIDTH;
        $h = self::AVATAR_HEIGHT;

        $img = imagecreatetruecolor($w, $h);
        //这一句一定要有
        imagesavealpha($img, true);
        //拾取一个完全透明的颜色,最后一个参数127为全透明
        $bg = imagecolorallocatealpha($img, 255, 255, 255, 127);
        imagefill($img, 0, 0, $bg);

        $r = $des_w / 2; //圆半径
        for ($x = 0; $x < $w; $x++)
        {
            for ($y = 0; $y < $h; $y++)
            {
                $rgbColor = imagecolorat($zoom_img, $x, $y);
                if (((($x - $r) * ($x - $r) + ($y - $r) * ($y - $r)) < ($r * $r)))
                {
                    imagesetpixel($img, $x, $y, $rgbColor);
                }
            }
        }

        //返回资源
        if (!$saveName) return $img;

        //输出图片到文件
        $settingDir = RUNTIME_PATH . 'active_fortune_year';
        if (!is_dir($settingDir))
        {
            if (!mkdir($settingDir, 0755, true) && !is_dir($settingDir))
            {
                throw new \RuntimeException(sprintf('Directory "%s" was not created', $settingDir));
            }
        }
        $filePath = $settingDir . DS . $saveName;

        imagepng($img, $filePath);
        //释放空间
        imagedestroy($src_img);
        imagedestroy($img);
        imagedestroy($zoom_img);
    }

}
